﻿using System.Web.Mvc;
using InvoiceInvoker.Logic.Repositories;
using InvoiceInvoker.MvcUI.Helpers;
using InvoiceInvoker.MvcUI.Models;
using InvoiceInvoker.Logic;

namespace InvoiceInvoker.MvcUI.Controllers
{
	[Authorize]
	[HandleError]
    public class ProfileController : Controller
    {
		private RegisteredSellerRepository _repository = new RegisteredSellerRepository();
		private int _sellerId;

		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			this.SetSellerId();
			_sellerId = (int)Session["SellerId"];

			base.OnActionExecuting(filterContext);
		}

        //
        // GET: /Profile/

        public ActionResult Index()
        {
			SellerModel seller = new SellerModel(_repository.GetById(_sellerId));

            return View(seller);
        }

		// POST: /Profile/

		[HttpPost]
		public ActionResult Index(SellerModel seller)
		{
			if (ModelState.IsValid)
			{
				ViewData["Message"] = "(zapisano zmiany)";

				RegisteredSeller toUpdate = _repository.GetById(seller.Id);
				RegisteredSeller updated = seller.ToRegisteredSeller();

				InvoiceNumber numberToUpdate = new InvoiceNumber(toUpdate.LastInvoiceNumber, toUpdate.InvoiceNumberFormat);
				InvoiceNumber numberUpdated = new InvoiceNumber(numberToUpdate.Number, numberToUpdate.Month, numberToUpdate.Year, updated.InvoiceNumberFormat);

				updated.LastInvoiceNumber = numberUpdated.ToString();

				_repository.Update(updated);
			}

			return View(seller);
		}

		//
		// GET: /Profile/InvoiceNumberFormatInfo/

		public ActionResult InvoiceNumberFormatInfo()
		{
			return View();
		}

    }
}
